﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MTGScore_Cards.Resources;
using Microsoft.Phone.Tasks;
using System.Threading;

namespace MTGScore_Cards
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor

        public static string MTGScore_ID = "5b8e1d81-a866-e011-81d2-78e7d1fa76f8";
        public static string MTGCards_ID = "8e788bb0-9067-e011-81d2-78e7d1fa76f8";
        public static string MTGHelps_ID = "8ee0b8fe-8e67-e011-81d2-78e7d1fa76f8";
        public static string MTGDice_ID = "db4da84e-5768-e011-81d2-78e7d1fa76f8";
        public static string InformaTreni_ID = "75c4de83-134c-e011-854c-00237de2db9e";
        public static string ChainingExplosion_ID = "6f6e33a9-6558-e011-854c-00237de2db9e";
        public static string EbookReader_ID = "c7ded5b0-17d6-df11-a844-00237de2db9e";
        //public static string Enigma_ID = "ad6556b4-bf71-e011-81d2-78e7d1fa76f8";
        public static string IdeoPuzzle_ID = "f7ffd022-63dc-df11-a844-00237de2db9e";
        public static string TriangleShooter_ID = "a08a8336-3cfe-df11-9264-00237de2db9e";
        public static string SpaceBattle_ID = "0ee14cb1-cad9-df11-a844-00237de2db9e";
        public static string TapSequence_ID = "3cf38972-3573-e011-81d2-78e7d1fa76f8";
        public static string BoardGameSuite_ID = "e8201966-ff70-e011-81d2-78e7d1fa76f8";
        public static string Enigma_ID = "ad6556b4-bf71-e011-81d2-78e7d1fa76f8";
        public MainPage()
        {
            InitializeComponent();
            currentResult = new SearchResult();
            DataContext = App.ViewModel;
            Ads_List.ItemsSource = App.ViewModel.Ads;
            Microsoft.Advertising.Mobile.UI.AdControl.TestMode = false;
            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };

            if (App.CurrentTheme == App.Theme.Dark)
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
            else
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
            credits.Click += OpenCredits_Button_Click;
            ApplicationBar.Buttons.Add(credits);
            

            try
            {
                var occ = Research.LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                {
                    Research.getHTML(Research.GetUtilizationUrl(occ, false),
                        (s) =>
                        {
                            Research.DeleteUtilizations();
                        },
                        () =>
                        {
                            Research.SaveUtilizations(occ);
                        });
                })).Start();
            }
            catch { }
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }
        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }
        SearchResult currentResult;
        string current_query;
        private void Results_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //DA FARE
            if (Results_List.SelectedItem == null)
                return;
            try
            {
                

                CardViewModel item = (CardViewModel)Results_List.SelectedItem;

                //for (int i = 0; i < currentResult.cards.Count; i++)
                if (item.Name.Equals(Strings.BuyFullVersion))
                {
                    OpenMarket();
                    return;
                }
                else if (item.Name.Equals(Strings.OthersCards))
                {
                    int val = currentResult.cards[currentResult.cards.Count - 1].succ;
                    if (val != 0)
                    {
                        var query = current_query + "&card_next=" + val;
                        Research.getHTML(query, GotHTML, ErrorGettingHTML);
                        EnableProgressBar();
                    }
                }
                else
                {
                    for (int i = 0; i < currentResult.cards.Count; i++)
                    {
                        var c = currentResult.cards[i];
                        if (c.name == item.Name as string)
                        {
                            PhoneApplicationService.Current.State.Remove("SelectedCard");
                            PhoneApplicationService.Current.State.Add("SelectedCard", c);
                            NavigationService.Navigate(new Uri("/CardPage.xaml", UriKind.Relative));
                            Results_List.SelectedItem = null;
                            break;
                        }
                    }
                }



            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            
        }
        public static bool showProducts = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (showProducts)
            {
                showProducts = false;
                Ads2_Button_Click(null, null);
            }
        }
        private void Search_Button_Click(object sender, RoutedEventArgs e)
        {




            

            //Results_List.Items.Clear();
            App.ViewModel.Cards.Clear();
            currentResult.cards.Clear();
            //current_query = "http://venetomagic.altervista.org/magic/magic_result2.php?card_name=" + Search_Text_Area.Text;
            current_query = "http://venetomagic.altervista.org/magic/magic_result2_test.php?card_name=" + Search_Text_Area.Text;
            Research.getHTML(current_query, GotHTML, ErrorGettingHTML);
            Dispatcher.BeginInvoke(() => EnableProgressBar());



        }

        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }
        private void BuildResults()
        {
            if (currentResult == null || currentResult.cards.Count == 0)
                return;
            //if (isTrial)
            //    Results_List.Items.Clear();
            //else
            //Results_List.Items.Clear();
            //for (int i = 0; i < Results_List.Items.Count; i++)
            //{
            //    string c = ((ListBoxItem)Results_List.Items[i]).Content as string;
            //    if (c == Strings.OthersCards || c == " ")
            //    {
            //        Results_List.Items.Remove(Results_List.Items[i]);
            //        i--;
            //    }
            //}
            //int max = isTrial ? Math.Min(1, currentResult.cards.Count) : currentResult.cards.Count;
            //for (int i = 0; i < max; i++)
            //{
            //    if (currentResult.cards[i].succ == 0)
            //        Results_List.Items.Add(new ListBoxItem() { Content = currentResult.cards[i].name, FontSize = 30 });
            //    else
            //    {
            //        Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //        Results_List.Items.Add(new ListBoxItem() { Content = Strings.OthersCards, FontSize = 30 });
            //        Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //        break;
            //    }
            //}
            //if (isTrial)
            //{
            //    Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //    Results_List.Items.Add(new ListBoxItem() { Content = Strings.BuyFullVersion, FontSize = 30 });
            //}

            App.ViewModel.Cards.Clear();
            for (int i = 0; i < App.ViewModel.Cards.Count; i++)
            {
                string c = (App.ViewModel.Cards[i]).Name as string;
                if (c == Strings.OthersCards || c == " ")
                {
                    App.ViewModel.Cards.Remove(App.ViewModel.Cards[i]);
                    i--;
                }
            }
            int max = currentResult.cards.Count;
            for (int i = 0; i < max; i++)
            {
                if (currentResult.cards[i].succ == 0)
                {
                    var c = currentResult.cards[i];
                    string desc = "";
                    if (c.edictions.Count != 0)
                        desc = Strings.Editions + c.edictions.Count + "; ";
                    if (c.languages.Count != 0)
                        desc += Strings.Languages + c.languages.Count + ";";
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = currentResult.cards[i].name, Description = desc });
                }
                else
                {
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = Strings.OthersCards });
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                    break;
                }
            }
            
                //App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                App.ViewModel.Cards.Add(new CardViewModel() { Name = Strings.BuyFullVersion });
            



            Results_List.SelectedItem = null;
            if (Results_List.Items.Count > 0)
                Results_List.ScrollIntoView(Results_List.Items.Last());
        }

        private void GotHTML(string html)
        {
            try
            {
                if (currentResult.cards.Count == 0)
                    currentResult = new ResultsParser(html).GetResults();
                else
                {
                    if (currentResult.cards.Last().succ != 0)
                        currentResult.cards.Remove(currentResult.cards.Last());
                    var newCards = new ResultsParser(html).GetResults().cards;

                    for (int i = 0; i < newCards.Count; i++)

                        currentResult.cards.Add(newCards[i]);
                }
                if (currentResult.cards.Count == 0)
                {
                    ErrorGettingHTML();
                    return;
                }
                //html = html.Replace("\n", "").Replace("\t", "");
                //byte[] byteArray = Encoding.Unicode.GetBytes(html);

                //MemoryStream stream = new MemoryStream(byteArray);
                //StreamReader s = new StreamReader(stream);
                //XmlSerializer serializer = new XmlSerializer(typeof(SearchResult));
                //currentResult = serializer.Deserialize(s) as SearchResult;
                //var c = serializer.Deserialize(s) as cards;

                Dispatcher.BeginInvoke(() => BuildResults());
            }
            catch (Exception e)
            {
                e.ToString();
            }
            finally
            {
                Dispatcher.BeginInvoke(() => DisableProgressBar());

            }
        }
        private void EnableProgressBar()
        {
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.IsIndeterminate = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void DisableProgressBar()
        {
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void ErrorGettingHTML()
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(Strings.ErrorGettingData);
                DisableProgressBar();
            });
            //ToggleProgressBar.IsEnabled = false;
            //ToggleProgressBar.IsIndeterminate = false;
            //ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Search_Text_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Search_Button_Click(null, null);
                Focus();
            }
        }

        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);

            
        }


        private void Ads1_Button_Click(object sender, RoutedEventArgs e)
        {
            OpenMarket(MTGCards_ID);
        }

        private void Ads2_Button_Click(object sender, RoutedEventArgs e)
        {
            PivotControl.SelectedItem = AdsPivot_Name;
        }

        private void OpenMarket()
        {
            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();

            marketplaceDetailTask.Show();
        }

        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }

        private void AdControl_AdControlError(object sender, Microsoft.Advertising.Mobile.UI.ErrorEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                Ads2_Button.Visibility = System.Windows.Visibility.Visible;
                AdControl.Visibility = System.Windows.Visibility.Collapsed;
            });
            
        }

        
    }
}